package com.boyicloud.exchangeserver.config

import com.boyicloud.exchangeserver.common.ResponseUtil
import com.boyicloud.exchangeserver.common.Result
import com.boyicloud.exchangeserver.common.TokenManager
import com.boyicloud.exchangeserver.security.LoginAuthFilter
import com.boyicloud.exchangeserver.security.TokenAuthFilter
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.Configuration
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.annotation.web.builders.WebSecurity
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder
import org.springframework.web.cors.CorsUtils

@Configuration
@EnableWebSecurity
class SecurityConfig : WebSecurityConfigurerAdapter() {


    @Autowired
    lateinit var tokenManager: TokenManager

    override fun configure(http: HttpSecurity) {
        http.exceptionHandling()
            .authenticationEntryPoint { _, resp, _ ->
                ResponseUtil.out(resp, Result(success = false, data = "", errMessage = "未登录，请先登录！"))
            }
            .and().csrf().disable().cors()
            .and().authorizeRequests().requestMatchers(CorsUtils::isPreFlightRequest).permitAll()
            .anyRequest().authenticated()
            .and().addFilter(LoginAuthFilter(authenticationManager(), tokenManager))
            .addFilter(TokenAuthFilter(authenticationManager(), tokenManager))
            .httpBasic()
    }

    override fun configure(web: WebSecurity) {
        web.ignoring().antMatchers("/status/**")
    }

    override fun configure(auth: AuthenticationManagerBuilder) {
        auth.inMemoryAuthentication().passwordEncoder(BCryptPasswordEncoder())
            .withUser("boyi").password(BCryptPasswordEncoder().encode("boyi4346")).roles("admin")
    }
}